<template>
  <a-spin :spinning="loading">
    <a-card title="官方搭配">
      <a-row type="flex" justify="start" align="top" class="mb-20" v-if="isOfficial">
        <a-col :md="layout.md.label" :lg="layout.lg.label" class="text-right"> 官方搭配图 </a-col>
        <a-col :md="layout.md.web" :lg="layout.lg.web">
          <div class="collocationPicBox">
            <img :src="details.mallImage" class="collocationPic" alt="" />
            <div class="plo">
              <a-icon type="eye" @click="preview(details.mallImage)" />
            </div>
          </div>
        </a-col>
      </a-row>

      <a-row type="flex" justify="start" align="top" class="mb-20">
        <a-col :md="layout.md.label" :lg="layout.lg.label" class="text-right"> *搭配商品 </a-col>
        <a-col :md="layout.md.web" :lg="layout.lg.web" v-if="details.collocationModelDetailsInfoDTOList.length > 0">
          <a-table :rowKey="record => record.productNo + record.sorting" :columns="columns" :data-source="details.collocationModelDetailsInfoDTOList" :pagination="false" bordered>
            <span slot="action" slot-scope="text, record, index">
              <a-icon type="arrow-up" class="sort" @click="move(index, 'up')" v-if="index > 1" />
              <a-icon type="arrow-down" class="sort" :class="{ 'ml-10': index > 1 }" @click="move(index, 'down')" v-if="index > 0 && index < details.collocationModelDetailsInfoDTOList.length - 1" />
              <a @click="removeCollocation(record.id, index)" class="ml-10" v-if="index > 0">删除</a>
            </span>
            <span slot="xh" slot-scope="text, record, index">{{ index + 1 }}</span>
            <template slot="goods" slot-scope="text, record, parentIndex">
              <div class="goods">
                <img class="skc-image" :src="record.image =='' && record.collocationProductList[0].image == '' ? 'https://picttype1.jnby.com/collocation/image-empty.png':record.image || record.collocationProductList[0].imag" />
                <div>
                  <div class="title">
                    <span>[{{ record.collocationProductList[0].brandName }}]</span><span>{{ record.collocationProductList[0].productName }}</span>
                  </div>
                  <div>
                    <!-- {{record.productAttrId}} -->
                    <a-select :defaultValue="record.collocationProductList[0].colorCode" v-model="record.colorCode" style="width: 200px" @change="handleSelectChange">
                      <a-select-option :value="option.colorCode" @click="updateItem(option, parentIndex)" v-for="option in record.collocationProductList" :key="option.colorCode">
                        {{ option.colorCode + '/' + option.colorName }}
                      </a-select-option>
                    </a-select>
                  </div>
                </div>
              </div>
            </template>
          </a-table>
          <a-button style="padding: 0" type="link" v-if="details.collocationModelDetailsInfoDTOList.length < 7" @click="showAdd = true">+添加搭配单品</a-button>
        </a-col>
      </a-row>
      <a-row type="flex" justify="start" align="top" class="mb-20">
        <a-col :md="layout.md.label" :lg="layout.lg.label" class="text-right"> 搭配风格(多选) </a-col>
        <a-col :md="layout.md.web" :lg="layout.lg.web">
          <a-checkbox-group @change="handleCheckboxChange" :value="details.labelNameId">
            <a-checkbox :value="item.code" v-for="item in lableList" :key="item.id">{{ item.name }}</a-checkbox>
          </a-checkbox-group>
        </a-col>
      </a-row>

      <a-row type="flex" justify="start" align="top" class="mb-20" v-if="!isOfficial">
        <a-col :md="layout.md.label" :lg="layout.lg.label" class="text-right"> *搭配图(多选) </a-col>
        <a-col :md="layout.md.web" :lg="layout.lg.web">
          <a-row>
            <a-col :span="24">
              <a-radio-group @change="handleRadioChange" :options="radioOptions" :value="radioValue"> </a-radio-group>
            </a-col>
            <a-col :span="24" v-if="radioValue == 'look'">
              <div class="collocationPicBox" v-if="url">
                <img :src="url" class="collocationPic" alt="" />
                <div class="plo">
                  <a-icon type="eye" @click="preview(url)" />
                  <a-icon class="ml-10" @click="url = ''" type="delete" />
                </div>
              </div>
              <div>
                <ChoiceLook :visible="visible" @confirm="confirm" />
                <a-button class="mt-20" type="link" @click="visible = !visible">{{ '选择其他搭配图' }}</a-button>
              </div>
            </a-col>
            <a-col :span="24" v-else class="mt-20">
              <aliossImageUpload v-model="url" />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <a-row type="flex" justify="start" align="top" class="mb-20">
        <a-col :md="{ span: layout.md.web.span, offset: layout.md.label.span }" :lg="{ span: layout.lg.web.span, offset: layout.lg.label.span }">
          <a-button type="primary" @click="complate">完成</a-button>
        </a-col>
        <a-col class="mt-20" :md="{ span: layout.md.web.span, offset: layout.md.label.span }" :lg="{ span: layout.lg.web.span, offset: layout.lg.label.span }" v-if="!isOfficial">
          <p class="tip">* 该素材已同步至买家秀，如果继续同步可能会在单品详情页内买家秀和单品搭配区域中重复出现</p>
        </a-col>
      </a-row>
      <PreviewImgVue :showPreviewImg.sync="showPreviewImg" :url="previewImgUrl" />
      <a-modal title="添加搭配商品" :visible="showAdd" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
        <a-input v-model="addSKC" placeholder="输入SKC进行添加"></a-input>
        <p>*请保证添加的商品在伯俊已完善SKU信息，否则，将无法添加成功</p>
      </a-modal>
    </a-card>
  </a-spin>
</template>
<script>
import aliossImageUpload from '@comp/aliossImageUpload'
import ChoiceLook from '../components/ChoiceLook.vue'
import PreviewImgVue from '../components/PreviewImg.vue'
import { getDetails, removeGoods, addGoods, getLable, updateCollcation,lookLabel } from '@/api/micromall/collocation.js'
import { up, down } from '../util/utils'
const columns = [
  {
    // dataIndex: 'name',
    title: '序号',
    scopedSlots: { customRender: 'xh' }
  },
  {
    title: '商品',
    dataIndex: 'age',
    scopedSlots: { customRender: 'goods' }
  },
  {
    title: '款号',
    dataIndex: 'productNo'
  },

  {
    title: '操作',
    width: 200,
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    aliossImageUpload,
    ChoiceLook,
    PreviewImgVue
  },
  data() {
    return {
      data: [],
      details: {
        mallImage: '',
        collocationModelDetailsInfoDTOList: [],
        labelNameId: []
      },
      id: '',
      columns,
      layout: {
        md: {
          label: { span: 3 },
          web: { span: 20 }
        },
        lg: {
          label: { span: 3 },
          web: { span: 20 }
        }
      },
      options: [
        { label: 'Apple', value: 'Apple' },
        { label: 'Pear', value: 'Pear' },
        { label: 'Orange', value: 'Orange' }
      ],
      radioOptions: [
        { label: '从LOOK库选图', value: 'look' },
        { label: '上传图片', value: 'upload' }
      ],
      url: '',
      value: [],
      visible: false,
      radioValue: 'look',
      showPreviewImg: false,
      previewImgUrl: '',
      showAdd: false,
      confirmLoading: false,
      addSKC: '',
      lableList: [],
      loading: false
    }
  },
  computed: {
    isOfficial() {
      console.log(this.$route.query.type)
      return this.$route ? this.$route.query.type == 'official' : false
    },
    formartlabelName() {
      return function (lables) {
        if (lables == '') {
          return []
        } else if (Array.isArray(lables)) {
          return lables
        }
        return lables.split(',')
      }
    }
  },
  created() {
    this.getDetails()
    this.getLable()
  },
  methods: {
    async complate() {
      this.loading = true
      const { details } = this
      const { id, differencePage } = this.$route.query
      const { collocationModelDetailsInfoDTOList, labelNameId, lookId } = details
      console.log(labelNameId)
      // if (labelNameId == '' || labelNameId.length < 1) {
      //   this.loading = false
      //   return this.$message.error('请至少选择一项搭配风格')
      // }
      const saveCollocationModelDtoList = collocationModelDetailsInfoDTOList.slice(1).map((item, index) => {
        return {
          productNoModel: item.productNo,
          sorting: index + 1,
          productAttrIdModel: item.productAttrId,
          colorCode: item.colorCode,
          colorName: item.colorName,
          id:item.id
        }
      })
      const params = {
        id,
        lookId,
        labelNameId: labelNameId.join(','),
        status: 2,
        differencePage,
        productAttrIdMain: collocationModelDetailsInfoDTOList[0].productAttrId,
        colorCode: collocationModelDetailsInfoDTOList[0].colorCode,
        colorName: collocationModelDetailsInfoDTOList[0].colorName,
        saveCollocationModelDtoList
      }
      const res = await updateCollcation(params)
      this.loading = false
      if (res.code == 200) {
        const toast = id ? '编辑':'添加'
        this.$message.success(toast + '官方搭配成功')
        this.$router.replace({
          path: `/micromall/marketing/collocation/official`
        })
        // this.$router.back()
      }else{
        this.$message.error(res.msg)
      }
      console.log(res)
    },
    async getLable() {
      const re = await lookLabel({code:'B08-A01'})
      this.lableList = re.data
    },
    async handleOk() {
      if (this.addSKC == '') {
        return this.$message.error('输入SKC进行添加')
      }
      this.confirmLoading = true
      const params = {
        productNoSkc: this.addSKC,
        mainId: this.$route.query.id
      }
      const re = await addGoods(params)
      this.confirmLoading = false
      if (re.code == 200) {
        this.details.collocationModelDetailsInfoDTOList.push(re.data)
        this.handleCancel()
        this.$message.success('添加成功')
      } else {
        this.$message.error(re.msg)
      }
    },
    handleCancel() {
      this.showAdd = false
      this.addSKC = ''
    },
    async removeCollocation(id, index) {
      const re = await removeGoods(id)
      console.log(re)
      if (re.code == 200) {
        this.$message.success('删除成功')
        this.details.collocationModelDetailsInfoDTOList.splice(index, 1)
      }
    },
    async getDetails() {
      this.loading = true
      const { id } = this.$route.query
      if (id) {
        const res = await getDetails(id)
        this.loading = false
        if (res.code == 200) {
          if (res.data && res.data.labelNameId && res.data.labelNameId.length > 0) {
            res.data.labelNameId = res.data.labelNameId.split(',')
          } else {
            res.data.labelNameId = []
          }
          this.details = res.data
        } else {
          this.$message.error(res.msg)
        }
      }
    },
    preview(url) {
      this.previewImgUrl = url
      this.showPreviewImg = true
    },
    confirm(url) {
      console.log('confirm', url)
      if (url) {
        this.url = url
      }
      this.visible = false
    },
    handleCheckboxChange(value) {
      this.details.labelNameId = value
    },
    handleRadioChange(e) {
      this.radioValue = e.target.value
    },
    handleSelectChange(e) {
      console.log(e)
    },
    updateItem({ id, colorCode, colorName, image }, parentIndex) {
      const item = this.details.collocationModelDetailsInfoDTOList[parentIndex]
      item.colorCode = colorCode
      item.colorName = colorName
      item.productAttrId = id
      item.image = image
      console.log(item)
      this.$set(this.details.collocationModelDetailsInfoDTOList, parentIndex, item)
    },
    move(index, method) {
      this.$set(
        this.details,
        'collocationModelDetailsInfoDTOList',
        method == 'up' ? up(index, this.details.collocationModelDetailsInfoDTOList, 1) : down(index, this.details.collocationModelDetailsInfoDTOList)
      )
    }
  }
}
</script>
<style scoped>
.mb-20 {
  margin-bottom: 20px;
}
.text-right {
  text-align: right;
  padding-right: 10px;
}
.mianPircture {
  width: 100px;
  height: auto;
}
.ml-10 {
  margin-left: 10px;
}
.mt-20 {
  margin-top: 20px;
}
.goods {
  display: flex;
  justify-content: start;
  align-items: center;
}
.skc-image {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}
.title {
  margin-bottom: 5px;
}
.collocationPic {
  width: 100%;
  height: auto;
}
.collocationPicBox {
  position: relative;
  padding: 10px;
  width: 170px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin-top: 20px;
}
.collocationPicBox:hover .plo {
  display: flex;
  justify-content: center;
  align-items: center;
}
.plo {
  display: none;
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  bottom: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 14px;
}
.tip {
  color: orange;
}
</style>
